import React, { useRef } from 'react'
import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'
import styles from './index.module.scss'
import { login, getCode } from '@/store/action/login'
import { useDispatch } from 'react-redux'
import { LoginForm } from '@/type/data'
import { useHistory } from 'react-router'
import { InputRef } from 'antd-mobile/es/components/input'
import { AxiosError } from 'axios'

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)

  const onGetCode = async () => {
    // 拿到手机号
    const mobile = form.getFieldValue('mobile')
    // console.log(mobile, '手机号')
    // 判断手机号校验是否成功
    const hasError = form.getFieldError('mobile').length > 0
    // console.log(hasError, '错误手机号')
    if (!mobile || hasError) {
      mobileRef.current?.focus()
      return
    }
    // 调用接口向mobile发验证码
    try {
      await dispatch(getCode(mobile))
      Toast.show({ content: '短信已发送' })
    } catch (err) {
      const error = err as AxiosError<{ message: string }>
      Toast.show({ content: error.response?.data.message })
    }
  }

  const onFinish = async (values: LoginForm) => {
    try {
      await dispatch(login(values))
      // 登录成功提示
      Toast.show({
        content: '登录成功',
        duration: 600,
        afterClose: () => {
          // 返回首页
          history.push('/home')
        }
      })
    } catch (err) {
      const error = err as AxiosError<{ message: string }>
      Toast.show({ content: error.response?.data.message })
    }
  }

  return (
    <div className={styles.root}>
      <NavBar />

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form onFinish={onFinish} form={form}
        initialValues={
         {
           mobile: 13911111111,
           code: '246810'
         }
        }
        >
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误'
              }
            ]}
          >
            <Input placeholder="请输入手机号" ref={mobileRef}/>
          </Form.Item>

          <List.Item
            className="login-code-extra"
            extra={<span className="code-extra" onClick={onGetCode}>发送验证码</span>}
          >
          <Form.Item
            className="login-item"
            name="code"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <Input placeholder="请输入验证码" autoComplete="off" />
          </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
